<?php

namespace app\goods\controller;

use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\extend\DataExtend;
use app\goods\model\ImsEweiShopGoods;
use app\goods\model\ImsEweiShopCategory;
use think\facade\Request;
use think\admin\service\AdminService;
use think\admin\service\MenuService;
use think\admin\service\NodeService;

class Category extends Controller
{
    public function index()
    {
        $this->title = '商品分类管理';
        $this->type = $this->get['type'] ?? 'index';
        // 获取顶分类单ID
        $this->pid = $this->get['pid'] ?? '';

        // 查询顶级分类集合
        $this->categorypList = ImsEweiShopCategory::mk()->where(['pid' => 0, 'status' => 1])->order('sort desc,id asc')->column('id,pid,name', 'id');
        ImsEweiShopCategory::mQuery()->layTable();
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        $data = DataExtend::arr2tree($data);
        // 回收站过滤有效分类
        if ($this->type === 'recycle') foreach ($data as $k1 => &$p1) {
            if (!empty($p1['sub'])) foreach ($p1['sub'] as $k2 => &$p2) {
                if (!empty($p2['sub'])) foreach ($p2['sub'] as $k3 => $p3) {
                    if ($p3['status'] > 0) unset($p2['sub'][$k3]);
                }
                if (empty($p2['sub']) && $p2['status'] > 0) unset($p1['sub'][$k2]);
            }
            if (empty($p1['sub']) && $p1['status'] > 0) unset($data[$k1]);
        }
        // 分类数据树数据变平化
        $data = DataExtend::arr2table($data);

        // 过滤非当前顶级分类的下级分类,并重新索引数组
        if ($this->type === 'index' && $this->pid) {
            $data = array_values(array_filter($data, function ($item) {
                return strpos($item['spp'], ",{$this->pid},") !== false;
            }));
        }
    }

    /**
     * 添加系统分类
     * @auth true
     */
    public function add()
    {
        $this->_applyFormToken();
        ImsEweiShopCategory::mForm('form');
    }

    /**
     * 编辑系统分类
     * @auth true
     */
    public function edit()
    {
        $this->_applyFormToken();
        ImsEweiShopCategory::mForm('form');
    }

    /**
     * 表单数据处理
     * @param array $vo
     */
    protected function _form_filter(array &$vo)
    {
        if ($this->request->isGet()) {
            $debug = $this->app->isDebug();
            /* 读取系统功能节点 */
            $this->auths = [];
            $this->nodes = MenuService::getList($debug);
            foreach (NodeService::getMethods($debug) as $node => $item) {
                if ($item['isauth'] && substr_count($node, '/') >= 2) {
                    $this->auths[] = ['node' => $node, 'title' => $item['title']];
                }
            }
            /* 选择自己上级分类 */
            $vo['pid'] = $vo['pid'] ?? input('pid', '0');
            /* 列出可选上级分类 */
            $categorys = ImsEweiShopCategory::mk()->order('sort desc,id asc')->column('id,name,pid,thumb,sort,status,isrecommand', 'id');
            $this->categorys = DataExtend::arr2table(array_merge($categorys, [['id' => '0', 'pid' => '-1', 'url' => '#', 'name' => '顶部分类']]));
            if (isset($vo['id'])) foreach ($this->categorys as $category) if ($category['id'] === $vo['id']) $vo = $category;
            foreach ($this->categorys as $key => $category) if ($category['spt'] >= 3) unset($this->categorys[$key]);
            if (isset($vo['spt']) && isset($vo['spc']) && in_array($vo['spt'], [1, 2]) && $vo['spc'] > 0) {
                foreach ($this->categorys as $key => $category) if ($vo['spt'] <= $category['spt']) unset($this->categorys[$key]);
            }
        }elseif ($this->request->isPost()) {

            
            if ($vo['pid'] == 0) {
                $vo['level'] = 1;
            }else{
                $pc = ImsEweiShopCategory::mk()->where(['id'=>$vo['pid']])->find();
                if (empty($pc)) {
                    $vo['level'] = 1;
                }else{
                    $vo['level'] = $pc['level']+1;
                }
            }
        }
    }

    /**
     * 修改分类状态
     * @auth true
     */
    public function state()
    {
        ImsEweiShopCategory::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除系统分类
     * @auth true
     */
    public function remove()
    {
        $ids_srt = Request::param('id');
        $ids_arr = array_unique(array_filter(explode(',', $ids_srt)));

        $goodsCount = ImsEweiShopGoods::mk()->where('merchid','in',$ids_arr)->count();

        if ($goodsCount) {
            $this->error('您所选分类存在商品，请先删除商品！');
        }
        ImsEweiShopCategory::mDelete();
    }
}
